//
//  CalibrateAccelerometer.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 12/4/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "CalibrateAccelerometer.h"

@implementation CalibrateAccelerometer

@synthesize _x = x, _y = y, _z = z;
@synthesize _originAngle = mOriginAngle;

+(CalibrateAccelerometer *) getInstance
{
    static CalibrateAccelerometer *mInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mInstance = [[CalibrateAccelerometer alloc] init];
    });
    
    return mInstance;
}

-(id) init
{
    if (self = [super init])
    {
        mLowPassFilter = [[LowpassFilter alloc] initWithSampleRate:60 cutoffFrequency:80];
    }
    
    return self;
}

-(void) setType:(ACCELEROMETER_TYPE)type
{
    if (type == eAT_TOP_DOWN)
    {
        mOriginAngle = -75;
    }
    else if (type == eAT_REGULAR)
    {
        mOriginAngle = -40;
    }
    else if (type == eAT_CUSTOM)
    {
        mSumCalibrate = 0;
        mCountCalibrate = 0;
    }
}

-(void) addSumCalibrate:(UIAcceleration *)acc
{
    mSumCalibrate += atan2f(acc.z, -acc.y);
    mCountCalibrate++;
}

-(void) averageOriginAngel
{
    mOriginAngle = CC_RADIANS_TO_DEGREES(mSumCalibrate / mCountCalibrate);
}

-(void) calibrate:(UIAcceleration *)acc
{
    [mLowPassFilter addAcceleration:acc];
    
    float angle = atan2f(mLowPassFilter.z, -mLowPassFilter.y);
    angle = mOriginAngle - CC_RADIANS_TO_DEGREES(angle);
    angle = min(TILT_WIDTH_IN_DEGREE, max(-TILT_WIDTH_IN_DEGREE, angle));
//    y = sinf(CC_DEGREES_TO_RADIANS(angle * TILT_FACTOR_IN_DEGREE));
    y = angle / TILT_WIDTH_IN_DEGREE;
//    CCLOG(@"angle = %f", angle);
    x = min(TILT_WIDTH_IN_RADIAN, max(-TILT_WIDTH_IN_RADIAN, mLowPassFilter.x));
    x /= TILT_WIDTH_IN_RADIAN;
    
    if (mOriginAngle > 0)
        x *= -1;
}

@end
